package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.common.BaseContext;
import com.reggie.entity.*;
import com.reggie.exception.CustomException;
import com.reggie.mapper.OrdersMapper;
import com.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    UserService userService;

    @Autowired
    AddressBookService addressBookService;

    @Autowired
    OrderDetailService orderDetailService;

//    提交订单
    @Transactional
    @Override
    public void submit(Orders orders) {
//    获取当前用户id
        Long currentId = BaseContext.getCurrentId();
//    查询当前用户 的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);
        if (shoppingCartList==null || shoppingCartList.size()==0){
            throw new CustomException("购物车为空,不能下单");
        }
//      查询用户数据
        User user = userService.getById(currentId);

//      查询地址信息
        AddressBook address = addressBookService.getById(orders.getAddressBookId());
        if (null== address){
            throw new CustomException("地址信息有误,不能下单");
        }

        long orderId = IdWorker.getId(); //订单号

        AtomicInteger amount=new AtomicInteger(0);

//        封装orderDetail表数据
        List<OrderDetail> orderDetails=shoppingCartList.stream().map((item)->{
           OrderDetail orderDetail=new OrderDetail();
           orderDetail.setOrderId(orderId);
           orderDetail.setNumber(item.getNumber());
           orderDetail.setDishFlavor(item.getDishFlavor());
           orderDetail.setDishId(item.getDishId());
           orderDetail.setSetmealId(item.getSetmealId());
           orderDetail.setName(item.getName());
           orderDetail.setImage(item.getImage());
           orderDetail.setAmount(item.getAmount());
            //          累加订单总金额
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());

           return orderDetail;
        }).collect(Collectors.toList());


//    向订单表插入数据

        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(String.valueOf(amount)));
        orders.setUserId(currentId);
        orders.setUserName(user.getName());
        orders.setPhone(address.getPhone());
        orders.setConsignee(address.getConsignee());
        orders.setNumber(String.valueOf(orderId));
        orders.setAddress(
                       (address.getProvinceName()==null? "":address.getProvinceName())
                      +(address.getCityName()==null ? "" : address.getCityName())
                      +(address.getDistrictName()==null ? "" : address.getDistrictName())
                      +(address.getDetail()==null ? "" : address.getDetail())
        );

        this.save(orders);

//    向订单明细表插入数据(可能是多条数据)

        orderDetailService.saveBatch(orderDetails);

//    清空购物车
        shoppingCartService.remove(queryWrapper);

    }

//    通过订单号获取订单明细
    @Override
    public List<OrderDetail> getOrderDetailByOrderNumber(Long id) {
        LambdaQueryWrapper<OrderDetail> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> list = orderDetailService.list(queryWrapper);
        return list;
    }

//    再来一单
    @Override
    public void again(Long id) {
//     因为订单表中的id和订单明细表中的orderId是一样的,
//     所以可以直接用传过来的id查订单明细表的数据
        LambdaQueryWrapper<OrderDetail> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> list = orderDetailService.list(queryWrapper);

//        清空现在的购物车
           LambdaQueryWrapper<ShoppingCart> shoppingCartQueryWrapper=new LambdaQueryWrapper<>();
           shoppingCartQueryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
           shoppingCartService.remove(shoppingCartQueryWrapper);

//        将订单明细的数据添加到购物车中
        List<ShoppingCart> shoppingCartList=list.stream().map((item)->{
            ShoppingCart shoppingCart=new ShoppingCart();
            shoppingCart.setName(item.getName());
            shoppingCart.setImage(item.getImage());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setDishId(item.getDishId());
            shoppingCart.setSetmealId(item.getSetmealId());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());

             return shoppingCart;
        }).collect(Collectors.toList());

        shoppingCartService.saveBatch(shoppingCartList);
    }
}
